const { getDb } = require('../database');

class NewsModel {
  /**
   * 获取所有新闻
   * @returns {Promise<Array>} 新闻列表
   */
  static async getAllNews() {
    const db = await getDb();
    return db.all('SELECT * FROM news');
  }

  /**
   * 根据ID获取新闻
   * @param {number} id - 新闻ID
   * @returns {Promise<Object|null>} 新闻信息
   */
  static async getNewsById(id) {
    const db = await getDb();
    return db.get('SELECT * FROM news WHERE id = ?', [id]);
  }

  /**
   * 根据分类获取新闻
   * @param {number} class_real - 新闻分类
   * @returns {Promise<Array>} 新闻列表
   */
  static async getNewsByClass(class_real) {
    const db = await getDb();
    return db.all('SELECT * FROM news WHERE class_real = ?', [class_real]);
  }

  /**
   * 获取选中的新闻列表
   * @returns {Promise<Array>} 选中的新闻列表
   */
  static async getSelectedNews() {
    const db = await getDb();
    return db.all('SELECT * FROM news WHERE is_select = 1');
  }

  /**
   * 创建新闻
   * @param {Object} newsData - 新闻数据
   * @returns {Promise<number>} 新创建的新闻ID
   */
  static async createNews(newsData) {
    const { abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select } = newsData;
    const db = await getDb();
    const result = await db.run(
      'INSERT INTO news (abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select || 0]
    );
    return result.lastID;
  }

  /**
   * 更新新闻
   * @param {number} id - 新闻ID
   * @param {Object} newsData - 新闻数据
   * @returns {Promise<boolean>} 是否更新成功
   */
  static async updateNews(id, newsData) {
    const { abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select } = newsData;
    const db = await getDb();
    const result = await db.run(
      'UPDATE news SET abstract_real = ?, class_real = ?, news_title = ?, news_source = ?, news_time = ?, cover_image = ?, is_select = ? WHERE id = ?',
      [abstract_real, class_real, news_title, news_source, news_time, cover_image, is_select, id]
    );
    return result.changes > 0;
  }

  /**
   * 删除新闻
   * @param {number} id - 新闻ID
   * @returns {Promise<boolean>} 是否删除成功
   */
  static async deleteNews(id) {
    const db = await getDb();
    const result = await db.run('DELETE FROM news WHERE id = ?', [id]);
    return result.changes > 0;
  }

  /**
   * 统计各类别新闻数量
   * @returns {Promise<Array>} 各类别新闻数量统计
   */
  static async getNewsCountByClass() {
    const db = await getDb();
    return db.all('SELECT class_real, COUNT(*) as count FROM news GROUP BY class_real');
  }
}

module.exports = NewsModel;